﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Threading.Tasks;

namespace AsscerMVCN2512.Controllers
{
    public class AreaManagementController : Controller
    {
        AssetDBEntities1 db = new AssetDBEntities1();
         
        // GET: AreaManagement
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAreaData(int page, int limit, string strAreaName = null, string strAreaTypeID = null)
        {
            try
            {
                int offset = limit * (page - 1);

                string sql = "SELECT AreaID, AreaTypeID, AreaName, AreaReMark FROM AreaInfo WHERE 1=1";
                var parameters = new List<System.Data.SqlClient.SqlParameter>();

                if (!string.IsNullOrEmpty(strAreaName))
                {
                    sql += " AND AreaName LIKE @AreaName";
                    parameters.Add(new System.Data.SqlClient.SqlParameter("@AreaName", "%" + strAreaName + "%"));
                }

                if (!string.IsNullOrEmpty(strAreaTypeID) && int.TryParse(strAreaTypeID, out int areaTypeId))
                {
                    sql += " AND AreaTypeID = @AreaTypeID";
                    parameters.Add(new System.Data.SqlClient.SqlParameter("@AreaTypeID", areaTypeId));
                }

                // 保持正序排列：按 AreaID 升序排列
                sql += " ORDER BY AreaID ASC";

                List<AreaManagementInfoViewModel> list = db.Database.SqlQuery<AreaManagementInfoViewModel>(sql, parameters.ToArray()).ToList();
                var data = list.Skip(offset).Take(limit);

                db.Configuration.LazyLoadingEnabled = false;
                var json = new
                {
                    code = 0,
                    msg = "",
                    count = list.Count,
                    data = data
                };
                return Json(json, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<AreaManagementInfoViewModel>()
                }, JsonRequestBehavior.AllowGet);
            }
        }

        // 检查区域名称是否已存在
        public ActionResult IsAreaNameExists(string areaName, string excludeId)
        {
            if (string.IsNullOrEmpty(areaName))
            {
                return Json(new { code = 0 }, JsonRequestBehavior.AllowGet);
            }

            var exists = db.AreaInfo.Any(c => c.AreaName == areaName);

            if (!string.IsNullOrEmpty(excludeId) && int.TryParse(excludeId, out int id))
            {
                exists = db.AreaInfo.Any(c => c.AreaName == areaName && c.AreaID != id);
            }

            return Json(new { code = exists ? 1 : 0 }, JsonRequestBehavior.AllowGet);
        }

        // 添加区域
        [HttpPost]
        // 参数类型改为 AreaManagementInfoViewModel
        public ActionResult AddArea(AreaManagementInfoViewModel model)
        {
            ModelState.Remove("AreaID");

            if (ModelState.IsValid)
            {
                try
                {
                    if (db.AreaInfo.Any(c => c.AreaName == model.AreaName))
                    {
                        return Json(new { code = 1, msg = "区域名称已存在！" });
                    }

                    var newArea = new AreaInfo
                    {
                        AreaTypeID = model.AreaTypeID,
                        AreaName = model.AreaName,
                        AreaReMark = model.AreaReMark
                    };

                    db.AreaInfo.Add(newArea);
                    db.SaveChanges();
                    return Json(new { code = 0, msg = "添加成功！" });
                }
                catch (Exception ex)
                {
                    return Json(new { code = 1, msg = "添加失败：" + ex.Message });
                }
            }
            var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
            return Json(new { code = 1, msg = "数据验证失败！" + string.Join(" ", errors) });
        }
        // 删除区域
        [HttpPost]
        public ActionResult DeleteArea(int id)
        {
            try
            {
                // 参数验证
                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "参数错误：无效的区域ID" });
                }

                var areaToDelete = db.AreaInfo.Find(id);
                if (areaToDelete == null)
                {
                    return Json(new { code = 1, msg = "未找到该区域或已被删除！" });
                }

                // 检查是否有明细资产关联到此区域
                var relatedAssets = db.AssetDetailInfo.Where(a => a.AreaID == id).ToList();
                if (relatedAssets.Any())
                {
                    var assetNames = string.Join("、", relatedAssets.Take(3).Select(a => a.AssetDetailNum));
                    var moreInfo = relatedAssets.Count > 3 ? $"等{relatedAssets.Count}个资产" : "";

                    return Json(new
                    {
                        code = 1,
                        msg = $"该区域下有关联的资产[{assetNames}{moreInfo}]，无法删除！请先移除相关资产再删除区域。"
                    });
                }

                // 检查是否有资产使用记录关联到此区域
                var relatedRecords = db.AssetDetailRecordInfo.Where(r => r.AreaID == id).ToList();
                if (relatedRecords.Any())
                {
                    return Json(new
                    {
                        code = 1,
                        msg = $"该区域在资产使用记录中被引用（共{relatedRecords.Count}条记录），无法删除！"
                    });
                }

                // 开始事务，确保数据一致性
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        // 这里可以添加其他相关表的删除逻辑
                        // 例如：如果区域有关联的其他数据，需要一并处理

                        db.AreaInfo.Remove(areaToDelete);
                        db.SaveChanges();

                        transaction.Commit();

                        // 记录日志（可选）
                        // LogHelper.Info($"删除区域：{areaToDelete.AreaName}(ID:{areaToDelete.AreaID})");

                        return Json(new { code = 0, msg = "删除成功！" });
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        return Json(new { code = 1, msg = "删除失败，数据回滚：" + ex.Message });
                    }
                }
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException dbEx)
            {
                // 数据库更新异常
                return Json(new { code = 1, msg = "数据库操作失败：" + (dbEx.InnerException?.Message ?? dbEx.Message) });
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // LogHelper.Error($"删除区域异常：{ex.Message}", ex);

                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        // 更新区域
        [HttpPost]
        // 参数类型改为 AreaManagementInfoViewModel
        public ActionResult UpdateArea(AreaManagementInfoViewModel model)
        {
            if (ModelState.IsValid && model.AreaID > 0)
            {
                try
                {
                    if (db.AreaInfo.Any(c => c.AreaName == model.AreaName && c.AreaID != model.AreaID))
                    {
                        return Json(new { code = 1, msg = "区域名称已存在！" });
                    }

                    var areaToUpdate = db.AreaInfo.Find(model.AreaID);
                    if (areaToUpdate == null)
                    {
                        return Json(new { code = 1, msg = "未找到该区域！" });
                    }

                    areaToUpdate.AreaTypeID = model.AreaTypeID;
                    areaToUpdate.AreaName = model.AreaName;
                    areaToUpdate.AreaReMark = model.AreaReMark;

                    db.Entry(areaToUpdate).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return Json(new { code = 0, msg = "更新成功！" });
                }
                catch (Exception ex)
                {
                    return Json(new { code = 1, msg = "更新失败：" + ex.Message });
                }
            }
            return Json(new { code = 1, msg = "数据验证失败！" });
        }

      
    }
}